package singleton;

/**
 * 带有同步锁的单例模式
 *
 * 目的: 解决多线程调用单例
 * 实现:
 * 1. 使用synchronized修饰getInstance
 * 2. 使用synchronized代码块包含if
 * 
 * @author insight 
 * @since 2021/4/22
 */
public class SingletonWithSync {
    private static SingletonWithSync instance;

    private SingletonWithSync() {
        System.out.println("SingletonWithSync is Instantiated!");
    }

    /**
     * 使用同步代码块修饰
     */
    public static SingletonWithSync getInstance() {
        synchronized (SingletonWithSync.class) {
            if (instance == null) {
                instance = new SingletonWithSync();
            }
        }
        return instance;
    }
}